<template>
  <div>
    <a-row>
      <a-col :offset="6" :span="8">
        <a-card title="新增单位">
          <a-form v-bind="layout">
            <a-form-item label="名称" required="true" v-bind="validateInfos.name">
              <a-input v-model:value="addUnitData.name" />
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 8 }">
              <a-button type="primary" @click="add">确定</a-button>
              <a-button style="margin-left: 30px" @click="resetFields">重置</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive } from 'vue'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'

import { useUnitApi } from '@/api/chunfeng/unit'
import { AddUnitData } from '@/api/chunfeng/unit/interfaces'
import { Form } from 'ant-design-vue'

export default defineComponent({
  name: 'UnitAdd',
  setup() {
    const { executeCommandRequest } = useHttpRequest()

    const { addUnit } = useUnitApi()

    const addUnitData = reactive<AddUnitData>({
      name: '',
    })
    const rules = reactive({
      name: [
        {
          required: true,
          message: '请输入单位名称',
        },
      ],
    })

    const { resetFields, validate, validateInfos } = Form.useForm(addUnitData, rules)
    const layout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
    }

    function add() {
      validate<AddUnitData>().then((data) => {
        executeCommandRequest(addUnit(data), {
          message: '添加单位成功',
          callback: () => {
            resetFields()
          },
        })
      })
    }

    return {
      addUnitData,
      validateInfos,
      layout,
      add,
      resetFields,
    }
  },
})
</script>
